package com.study.crypto.basic.gb.handler;

import com.google.common.collect.ImmutableMap;
import com.study.crypto.basic.dto.ResponseRandomDto;
import com.study.crypto.basic.gb.exception.AuthenticationException;
import com.study.crypto.basic.gb.exception.GbRuntimeException;
import com.study.crypto.basic.general.spring.handler.GeneralDefaultHandlerExceptionResolver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.security.SignatureException;
import java.time.Instant;
import java.util.Map;

/**
 * 统一异常处理
 *
 * @author Songjin
 * @since 2020/9/26 23:53
 */
@RestControllerAdvice
@Slf4j
public class DefaultHandlerExceptionResolver extends GeneralDefaultHandlerExceptionResolver {
    
    /**
     * 签名验签异常处理
     */
    @ExceptionHandler(SignatureException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Map<String, Object> resovleSignatureException(SignatureException e) {
        log.error("异常堆栈", e);
        return null;
    }
    
    /**
     * 国办异常处理
     */
    @ExceptionHandler(GbRuntimeException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, Object> resovleTokenInfoException(GbRuntimeException e) {
        log.error("异常堆栈", e);
        ResponseRandomDto randomDto = new ResponseRandomDto();
        randomDto.setResultCode("-1");
        String resultCodeMsg;
        if (e.getCode() == 901011) {
            resultCodeMsg = "随机数验证失败";
        } else if (e.getCode() == 901014) {
            resultCodeMsg = "验签失败";
        } else {
            resultCodeMsg = "";
        }
        randomDto.setResultCodeMsg(resultCodeMsg);
        randomDto.setTaskCode(e.getTaskCode());
        return ImmutableMap.<String, Object>builder()
                .put("code", e.getCode())
                .put("message", e.getMessage())
                .put("data", randomDto)
                .build();
    }
    
    /**
     * 鉴权异常处理
     */
    @ExceptionHandler(AuthenticationException.class)
    public Map<String, Object> resovleAuthenticationException(AuthenticationException e) {
        log.error("异常堆栈", e);
        return ImmutableMap.<String, Object>builder()
                .put("timestamp", Instant.now().toEpochMilli())
                .put("status", HttpStatus.UNAUTHORIZED.value())
                .put("error", HttpStatus.UNAUTHORIZED.getReasonPhrase())
                .put("message", e.getMessage())
                .put("path", e.getPath()).build();
    }
    
}
